package com.qf.ym.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.ym.entity.RoleEntity;
import com.qf.ym.pojo.AuthPojo;
import com.qf.ym.pojo.RolePojo;
import com.qf.ym.service.AuthService;
import com.qf.ym.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class RoleController {

    @Autowired
    RoleService roleService;

    @Autowired
    AuthService authService;
    //添加角色权限信息
    @RequestMapping("/addRole")
    public String addRole(RoleEntity re){

        boolean result=roleService.addRole(re);

        return "success";
    }
    //跳转角色添加页面,获取角色权限信息
    @RequestMapping("jumpRole")
    public String jumpRole(int rid,HttpServletRequest request){
        //获取所有的权限
        List<AuthPojo> authlist = authService.queryAuths();
        request.setAttribute("authlist",authlist);


        RolePojo role = roleService.queryRolesBid(rid);
        request.setAttribute("role",role);
        //获取当前角色的所有权限
        List<AuthPojo> auths = role.getAuths();
        request.setAttribute("auths",auths);

        return "roleadd";
    }
    //编辑角色，展示权限
    @RequestMapping("editRole")
    public String editRole(RoleEntity re,HttpServletRequest request){
        boolean result=roleService.editRole(re);
        if(result){
            return "addsuccess";
        }else {
            request.setAttribute("msg","编辑失败");
            return "roleedit";
        }

    }
    //显示编辑页面角色当前存在的信息
    @RequestMapping("jumpRoleEdit")
    public String pageEditRole(int rid, HttpServletRequest request){
        //查询当前角色信息
         RolePojo rolePojo= roleService.queryRolesBid(rid);
         //查询所有权限信息
        List<AuthPojo> auths = rolePojo.getAuths();
        //查询所有权限信息
        List<AuthPojo> authPojos = authService.queryAuths();

        for(AuthPojo ap:authPojos){

            for(AuthPojo at:auths){
                //用户存在这个权限
                if(ap.getAuid()==at.getAuid()){

                    ap.setChicked(true);

                }

            }

        }
        ObjectMapper om = new ObjectMapper();
        try {
            String s = om.writeValueAsString(auths);
            String s1 = om.writeValueAsString(authPojos);
            request.setAttribute("s",s);
            request.setAttribute("s1",s1);
            request.setAttribute("role",rolePojo);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "roleedit";
    }








}
